(function () {
    // 私有变量
    const addBtn = document.querySelector('#add-book-btn');
    const modal = document.querySelector('.modal');
    const closeModalBtn = document.querySelector('#close-form-btn');
    const tbody = document.querySelector('tbody');
    const form = document.querySelector('#book-form');
    const searchBox = document.querySelector("#search-box");
    const formTitle = document.querySelector("#form-title");

    // 表单选项
    let itemId = document.querySelector("#book-id");
    let itemName = document.querySelector("#book-name");
    let itemAuthor = document.querySelector("#author");
    let itemPublisher = document.querySelector("#publisher");



    let data = [];
    // api接口设置
    const API_BASE_URL = "http://localhost/book";

    // 搜索图书# 修改bookName
    function searchBooks(query) {
        axios.get(API_BASE_URL + `?bookName=${query}`).then(res => {
            if (res.data.code === 500) {
                alert(`${res.data.msg}`);
                return;
            }
            data = res.data.data;
            renderTable(data);
        });
    }

    // 渲染表格数据 # 修改item.后面的属性名称
    function renderTable(data) {
        if (data.length === 0) return alert("无内容");
        tbody.innerHTML = data.map(item => {
            return `<tr data-id="${item.bookId}">
                <td>${item.bookId}</td>
                <td>${item.bookName}</td>
                <td>${item.bookAuthor}</td>
                <td>${item.bookPublisher}</td>
                <td>
                    <button class="update-btn">修改</button>
                    <button class="delete-btn">删除</button>
                </td>
            </tr>`;
        }).join('');

        // 添加事件监听器（事件委托）
        tbody.addEventListener('click', handleTableClick);
    }

    // 更新图书时，先回显要被修改的旧数据
    function updateBook(id) {
        axios.get(API_BASE_URL + `/${id}`).then(res => {
            const data = res.data.data;
            showOrCloseModal();
            form.reset();
            // ########以下内容要修改##########

            formTitle.innerText = '更新图书';
            itemId.value = data.bookId;
            itemName.value = data.bookName;
            itemAuthor.value = data.bookAuthor;
            itemPublisher.value = data.bookPublisher;

            //  ######以上内容要修改#####
        });
    }


    // 处理表格点击事件
    function handleTableClick(e) {
        if (e.target.classList.contains('delete-btn')) {
            deleteBook(e.target.closest('tr').dataset.id);
        } else if (e.target.classList.contains('update-btn')) {
            updateBook(e.target.closest('tr').dataset.id);
        }
    }

    // 开关浮层
    function showOrCloseModal(show = true) {
        if (show) {
            modal.style.display = 'block';
        } else {
            modal.style.display = 'none';
        }

        document.querySelector("#book-id").value = null; // 重置当前编辑的图书ID
    }

    // 获取列表
    function fetchBooks() {
        axios.get(API_BASE_URL).then(e => {

            data = e.data;

            renderTable(data);
        });

    }

    // 根据id删除
    function deleteBook(id) {
        if (!confirm("真的要删除吗?")) return;
        axios.delete(API_BASE_URL + `/${id}`).then(res => {
            if (res.data.code === 500) return alert(res.data.msg)
            alert(res.data.data);
            fetchBooks();
        });
    }



    // 点击保存按钮：添加或更新图书
    function saveBook() {
        // 获取表单项的值
        let bookId = itemId.value;
        const bookName = itemName.value;
        const bookAuthor = itemAuthor.value;
        const bookPublisher = itemPublisher.value;

        // 非空判断
        if (!bookName || !bookAuthor || !bookPublisher) {
            alert("所有字段都必须填写！");
            return;
        }

        // 表单项的值，封装成一个对象
        const book = {
            bookId: bookId || null, // 如果为空，则视为添加新图书
            bookName: bookName,
            bookAuthor: bookAuthor,
            bookPublisher: bookPublisher
        };

        // 根据编号判断是添加还是更新
        if (bookId) {
            axios.put(API_BASE_URL, book).then(res => {
                res.data.code === 200 ? alert(res.data.data) : alert(res.data.msg);
                fetchBooks();
                showOrCloseModal(false);
            })
        } else {
            axios.post(API_BASE_URL, book).then(res => {
                res.data.code === 200 ? alert(res.data.data) : alert(res.data.msg);
                fetchBooks();
                showOrCloseModal(false);
            })
        }

    }



    // 初始化事件监听器
    function init() {
        addBtn.addEventListener('click', () => {
            form.reset();
            formTitle.innerText = '添加图书';
            bookId = null;
            showOrCloseModal();
        });

        closeModalBtn.addEventListener('click', () => {
            bookId = null; // 重置当前编辑的图书ID
            showOrCloseModal(false);
        });

        form.addEventListener('submit', (e) => {
            e.preventDefault();
            saveBook();
        });

        searchBox.addEventListener('keyup', (e) => {
            if (e.key === "Enter") {
                searchBooks(searchBox.value);
                searchBox.value = '';
            }
        });

        // 初始加载图书列表
        fetchBooks();
    }

    // 执行初始化函数
    init();
})();